'''
Retrieve run history data, such as source type and station deployed to, from database. Else retrieve it
from run_history file
'''

import urllib
import json
import sys

def GetSourceFromFilename(filename):
    # check filename for source type
    for src in ['Ra', 'Th', 'Co', 'Cs']:
        if src  in filename:
            fnSrc = src
            break
        else:
            fnSrc = None
    return fnSrc


def StationCheck(station, finalPos):
    #Checks that station is the right one in the cases where there are multiple runs in a day.
    
    if station == 'S2' and finalPos > 320 and finalPos <= 366:
        return True
    elif station == 'S5' and finalPos > 366 and finalPos <= 419:
        return True
    elif station == 'S8' and finalPos > 419 and finalPos <= 474:
        return True
    elif station == 'S11' and finalPos > 474 and finalPos <= 525:
        return True
    else:
        return False


def SourceCheck(fnsrc):
    # If source is indicated in filename, as it is occasionnaly, takes that source as the run source
    
    source, strength = 'known', 'Un'
    
    if 'Ra' in fnsrc:
        source = 'Ra-226'
    elif 'Cs' in fnsrc:
        source = 'Cs-137'
    elif 'Co' in fnsrc:
        source = 'Co-60'
    elif 'Th' in fnsrc:
        source = 'Th-228'
    
    if 'w' in fnsrc:
        strength = 'weak'
    elif 'str' in fnsrc:
        strength = 'strong'
    else: # assume weak if None
        strength = 'weak'
    
    return source, strength


### also need to be able to read comments that say S5 + 1, etc for QC check
def GetSourcesStations(runDate, finalPos, filename):
    '''
    Gets source and station for run
    '''
    
    strength, source, station = 'Un', 'known', 'Unknown'
    
    # first try getting source/station from database
    try:
        openUrl = urllib.urlopen('http://exo-data.slac.stanford.edu/ExoDatacat/rest/runs?runMin=2000&runMax=')
        dataLines = json.loads(openUrl.readlines()[0])
        sortedDataLines = sorted(dataLines, key=lambda k: k['run'])
        for i in sortedDataLines:
            if i['runType'] != 'Data-Source calibration':
                continue
            if runDate not in i['startTime']:
                continue
            source = i['sourceType'].split(':')[0]
            strength = i['sourceType'].split(':')[1]
            station = i['sourcePosition'].split(':')[0]
            
            # check validity of station with final source position
            stationValid = StationCheck(station, finalPos)
            if stationValid == True:
                break
    
    # next try getting setting source/station from run_history.txt
    except:
    #if station == None: # have it update run history as it does this?
        file = open('run_history.txt')
        lines = file.readlines() #source position not always accurate - in comments section has like S5 + 1"
        for i, line in enumerate(lines):
            if runDate not in line:
                continue
            source = line.split(', ')[2].split(':')[0]
            strength = line.split(', ')[2].split(':')[1]
            station = line.split(', ')[-1].rstrip()
            
            # check validity of station with final source position
            stationValid = StationCheck(station, finalPos)
            if stationValid == True:
                break
            
        file.close()
    
    # get source from filename if it is written there
    fnSrc = GetSourceFromFilename(filename)
    if fnSrc != None:
        source, strength = SourceCheck(fnSrc)
    return strength + source, station

